package com.m.wechathelperforgroup;

import android.accessibilityservice.AccessibilityService;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by m on 2018/7/9.
 */

public class WechatAccessibilityService extends AccessibilityService {

    private final static String TAG = "MyAccessibilityService";
    private List<Linkman> notFound = new ArrayList<>();
    private String USER_URL = "http:39.106.133.74:8080/getLatestMem";
    private String GROUP_URL = "http:39.106.133.74:8080/getLatestChatroom";
    private Intent intent = new Intent(MainActivity.ACTION_SERVICE_STATE_CHANGE);
    private String user_result = null;
    private String group_result = "";

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
        int eventType = accessibilityEvent.getEventType();
        /*CharSequence classNameChr = accessibilityEvent.getClassName();
        String className = classNameChr.toString();
        Log.d(TAG, accessibilityEvent.toString());
        Log.d(TAG, "className " + className);*/

        switch (eventType) {
            case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED:

                break;
            case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                // 用户是否进入"发起群聊"界面
                if (isGroup()) {
                    // 开始群聊时就刷新一次接口
                    initLinkmans();

                    List<Linkman> linkmens = refreshLinkmans();

                    this.createGroup(linkmens);

                    String groupName = group_result;
                    renameGroup(groupName);

                    // 建群后数据重置
                    user_result = null;
                    notFound.clear();
                }
                break;
            default:

                break;
        }
    }


    // 下载接口数据
    private void initLinkmans() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    user_result = HttpUtil.getRequest(USER_URL);
                    group_result = HttpUtil.getRequest(GROUP_URL);
                } catch (IOException e) {
//                    e.printStackTrace();
                }
            }
        }).start();
    }

    // 解析联系人信息
    private List<Linkman> refreshLinkmans() {
        JsonArray jsonArray = new JsonArray();
        // 在数据刷新之前会重复等待
        while (user_result == null) {
            deplay();
        }
        if (user_result != null) {
            jsonArray = new JsonParser().parse(user_result).getAsJsonArray();
        }
        List<Linkman> linkmens = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JsonObject linkmanObject = jsonArray.get(i).getAsJsonObject();
            Linkman linkman = new Linkman();
            linkman.setWechatId(linkmanObject.get("weChatId").getAsString());
            linkman.setName(linkmanObject.get("name").getAsString());
            linkmens.add(linkman);
        }
        return linkmens;
    }

    // 建群
    private void createGroup(List<Linkman> linkmens) {
        for (Linkman linkmen : linkmens) {
            deplay();
            // 搜索框输入内容
            search(linkmen.getWechatId());
            deplay();
            // 选中
            chooseFriend(linkmen);
        }
        // 通知activity打印提示信息
        sendAction();
        deplay();
        confirmGroup();
    }

    //判断群聊界面
    private boolean isGroup() {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo != null) {
            List<AccessibilityNodeInfo> tabNodes = nodeInfo.findAccessibilityNodeInfosByViewId("android:id/text1");
            for (AccessibilityNodeInfo tabNode : tabNodes) {
                if (tabNode.getText().toString().equals("发起群聊")) {
                    return true;
                }
            }
        }
        return false;
    }

    // 搜索
    private void search(String wechatId) {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo != null) {
            List<AccessibilityNodeInfo> tabNodes = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/au7");
            for (AccessibilityNodeInfo tabNode : tabNodes) {
                if (tabNode.getText().toString().equals("搜索")) {
                    ClipboardManager clipboard = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clip = ClipData.newPlainText("text", wechatId);
                    clipboard.setPrimaryClip(clip);
                    // 焦点
                    tabNode.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
                    // 粘贴进入内容
                    tabNode.performAction(AccessibilityNodeInfo.ACTION_PASTE);
                    break;
                }
            }
        }
    }

    // 选中朋友
    private void chooseFriend(Linkman linkman) {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo != null) {
            List<AccessibilityNodeInfo> tabNodes = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/ib");
            for (AccessibilityNodeInfo tabNode : tabNodes) {
                if (tabNode.getText().toString().indexOf(linkman.getWechatId()) != -1) {
                    tabNode.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    return;
                }
            }
            // 没有联系人可选时
            notFound.add(linkman);
            // 直接搜下个人(情况搜索框)
            tabNodes = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/au7");
            for (AccessibilityNodeInfo tabNode : tabNodes) {
                if (tabNode.getText().toString().equals(linkman.getWechatId())) {
                    // 清空当前内容
                    tabNode.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT);
                    break;
                }
            }
        }
    }

    // 确定建群
    private void confirmGroup() {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo != null) {
            List<AccessibilityNodeInfo> tabNodes = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/hg");
            for (AccessibilityNodeInfo tabNode : tabNodes) {
                if (tabNode.getText().toString().startsWith("确定")) {
                    tabNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    break;
                }
            }
        }
    }

    // 修改群聊名称
    private void renameGroup(String groupName) {
        deplay();
        deplay();
        deplay();
        groupInfo();
        deplay();
        renameGroup0();
        deplay();
        renameGroup1(groupName);
        deplay();
        renameGroup2();

    }

    // 进入群信息界面
    private void groupInfo() {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo != null) {
            List<AccessibilityNodeInfo> tabNodes = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/hh");
            for (AccessibilityNodeInfo tabNode : tabNodes) {
                if (tabNode.getContentDescription().toString().equals("聊天信息")) {
                    tabNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    break;
                }
            }
        }
    }

    // 修改群名称
    private void renameGroup0() {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo != null) {
            List<AccessibilityNodeInfo> tabNodes = nodeInfo.findAccessibilityNodeInfosByViewId("android:id/title");
            for (AccessibilityNodeInfo tabNode : tabNodes) {
                if (tabNode.getText()!=null && tabNode.getText().toString().equals("群聊名称")) {
                    tabNode.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    break;
                }
            }
        }
    }

    // 修改群名称
    private void renameGroup1(String groupName) {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo != null) {
            List<AccessibilityNodeInfo> tabNodes = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/cgx");
            for (AccessibilityNodeInfo tabNode : tabNodes) {
                ClipboardManager clipboard = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("text", groupName);
                clipboard.setPrimaryClip(clip);
                // 焦点
                tabNode.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
                // 粘贴进入内容
                tabNode.performAction(AccessibilityNodeInfo.ACTION_PASTE);
                break;
            }
        }
    }

    // 修改群名称
    private void renameGroup2() {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo != null) {
            List<AccessibilityNodeInfo> tabNodes = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/hg");
            for (AccessibilityNodeInfo tabNode : tabNodes) {
                if (tabNode.getText().toString().equals("保存")) {
                    tabNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    break;
                }
            }
        }
    }

    // 延迟
    private void deplay() {
        try {
            Thread.sleep(1 * 1000L);
        } catch (Exception e) {

        }
    }

    @Override
    public void onInterrupt() {
        user_result = null;
        notFound.clear();
    }

    private void sendAction() {
        Bundle bundle = new Bundle();
        bundle.putSerializable("notFund", (Serializable) notFound);
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
